package cn.jflow.boot.controller;

import bp.da.DBAccess;
import bp.da.DataSet;
import bp.da.DataTable;
import bp.da.DataType;
import bp.port.Emp;
import bp.port.EmpAttr;
import bp.tools.Encodes;
import bp.web.WebUser;
import bp.wf.GenerWorkFlow;
import bp.wf.port.WFEmp;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@CrossOrigin(maxAge = 3600)
@RequestMapping("/BPM")
public class WebServiceController {
    /**
     * 系统登录
     * @return token
     * @throws Exception
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/SSOLogin")
    public JSONObject SSOLogin(@RequestBody Map<String,String> param)throws Exception{
        JSONObject res = new JSONObject();
        //帐号
        String userNo = param.get("userNo");
        //时间戳
        Long timestamp=Long.parseLong(param.get("timestamp"));
        //当前时间
        Long timesNow=System.currentTimeMillis();
        //获取当前分钟数
        Long mins=(timesNow-timestamp)/(1000*60);
        if(mins>5){
            res.put("code", 500);
            res.put("token",0);
            res.put("message","请求失效.");
            return res;
        }
        //签名
        String sign=param.get("sign");
        String userID="";
        String signStr=userNo+"_"+timestamp;
        String signMD5= Encodes.encodeBase64(signStr);
        //签名判断
        if(!signMD5.equals(sign)){
            res.put("code", 500);
            res.put("token",0);
            res.put("message","签名验证失败.");
            return res;
        }

        //String userID=systemNo+"_"+userNo;

        try{

            //验证用户信息
            Emp emps=new Emp();
            if(!emps.IsExit(EmpAttr.No,userNo))
            {
                res.put("code", 500);
                res.put("token",0);
                return res;
            }
            else{
                //写入用户信息
                bp.wf.Dev2Interface.Port_Login(userNo);

                res.put("code", 200);
                if(DataType.IsNullOrEmpty(WebUser.getToken())){
                    WFEmp wfEmp=new WFEmp(userNo);
                    if(DataType.IsNullOrEmpty(wfEmp.getToken())){
                        String wfTkoen= DBAccess.GenerGUID();
                        wfEmp.setToken(wfTkoen);
                        wfEmp.Update();
                        res.put("token", wfTkoen);
                    }
                    else
                        res.put("token", wfEmp.getToken());
                }
                else
                    res.put("token", WebUser.getToken());
                res.put("no",WebUser.getNo());
                res.put("fk_dept",WebUser.getFK_Dept());
                res.put("name",WebUser.getName());
                res.put("fk_depName",WebUser.getFK_DeptName());
                res.put("SID",WebUser.getSID());
                res.put("orgNo",WebUser.getOrgNo());
            }
        }
        catch(Exception ex){
            res.put("code", 500);
            res.put("token",0);
        }
        return res;
    }
    /**
     * 保存嵌入式表单数据接口
     * usrNo 发起人编号
     * flowNo 流程编号
     * workID 主键
     * maintable  填充表单
     * dtl 从表
     * @return
     */
    @PostMapping("/saveSelfWork")
    public JSONObject saveSelfWork(@RequestBody JSONObject param) throws Exception{
        JSONObject res = new JSONObject();
        //执行发送人员的帐号
        String userNo = param.get("userNo").toString();
        //要保存的流程编号
        String flowNo = param.get("flowNo").toString();
        //流程实例主键
        long workID=Long.parseLong(param.get("workID").toString());
        //主表单数据
        String mainTable = param.get("mainTable").toString();
        //从表数据
        JSONArray dtlsJSON = param.getJSONArray("dtls");
        if(workID==0){
            res.put("code",500);
            res.put("message","workID参数不能为0，请检查参数是否传递正确。");
            return res;
        }

        Hashtable<Object, Object> dataTable = new Hashtable();
        DataSet ds=new DataSet();
        DataTable dt = null;
        try{
            //写入用户信息
            bp.wf.Dev2Interface.Port_Login(userNo);
            GenerWorkFlow gwf=new GenerWorkFlow(workID);
            //表单填充
            if (StringUtils.isNotBlank(mainTable)){
                Map<String, Object> formMap = parseJSON2Map(JSONObject.fromObject(mainTable));
                formMap.forEach((key, value) -> dataTable.put(key,value));
            }
            //从表填充
            //可能有多个从表数据
            for(int i=0;i<dtlsJSON.size();i++){
                JSONObject dtlDatas = (JSONObject) dtlsJSON.get(i);
                //从表编号
                String dtlNo=dtlDatas.get("dtlNo").toString();
                //从表数据
                String dtlArryData=dtlDatas.get("dtl").toString();
                //生成table
                DataTable dtlDt=bp.tools.Json.ToDataTable(dtlArryData);
                dtlDt.TableName=dtlNo;
                ds.Tables.add(dtlDt);
            }

            bp.wf.Dev2Interface.Node_SaveWork(flowNo,gwf.getFK_Node(),workID,dataTable,ds,gwf.getFID(),gwf.getPWorkID());
            res.put("code",200);
            res.put("message","保存成功。");
        }
        catch (Exception ex){
            res.put("code",500);
            res.put("message",ex.getMessage());
        }
        return res;
    }

    public static Map<String, Object> parseJSON2Map(JSONObject json) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        // 最外层解析
        for (Object k : json.keySet()) {
            Object v = json.get(k);
            // 如果内层还是json数组的话，继续解析
            if (v instanceof JSONArray) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                Iterator<JSONObject> it = ((JSONArray) v).iterator();
                while (it.hasNext()) {
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2));
                }
                map.put(k.toString(), list);
            } else if (v instanceof JSONObject) {
                // 如果内层是json对象的话，继续解析
                map.put(k.toString(), parseJSON2Map((JSONObject) v));
            } else {
                // 如果内层是普通对象的话，直接放入map中
                map.put(k.toString(), v);
            }
        }
        return map;
    }
}
